package com.jd.product.controller;

import com.jd.product.service.IProductService;
import com.jd.product.domain.Product;
import com.jd.product.query.ProductQuery;
import com.jd.basic.util.AjaxsResult;
import com.jd.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
* 后端接口类；
*/
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    public IProductService productService;

    /**
     * 接口：添加或修改
     * @param product  传递的实体
     * @return AjaxsResult 响应给前端
     */
    @PutMapping
    public AjaxsResult save(@RequestBody Product product){
        try {
            if( product.getId()!=null)
                productService.update(product);
            else
                productService.save(product);
            return new AjaxsResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxsResult(false,"操作失败");
        }
    }

    /**
    * 接口：删除
    * @param id
    * @return AjaxsResult 响应给前端
    */
    @DeleteMapping(value="/{id}")
    public AjaxsResult remove(@PathVariable("id") Long id){
        try {
            productService.remove(id);
            return new AjaxsResult();
        } catch (Exception e) {
        e.printStackTrace();
            return new AjaxsResult(false,"删除失败");
        }
    }

    /**
    * 接口：批量删除
    * @param ids
    * @return AjaxsResult 响应给前端
    */
    @PatchMapping
    public AjaxsResult patchRemove(@RequestBody List<Long> ids){
        try {
                productService.patchRemove(ids);
            return new AjaxsResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxsResult(false,"批量删除失败");
        }
    }

    /**
    * 接口：查询单个对象
    * @param id
    */
    @GetMapping("/{id}")
    public Product findOne(@PathVariable("id")Long id) {
        return productService.loadById(id);
    }


    /**
    * 接口：查询所有
    * @return
    */
    @GetMapping
    public List<Product> findAll(){
        return productService.loadAll();
    }


   /**
    * 接口：分页查询或高级查询
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    public PageList<Product> queryPage(@RequestBody ProductQuery query) {
        return productService.queryPage(query);
    }
}
